package com.sfac.java_spring_boot_02.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Description ParameterFilter
 * @Author HymanHu
 * @Date 2021/9/17 8:52
 */
@WebFilter(filterName = "parameterFilter", urlPatterns = {"/*"})
public class ParameterFilter implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(ParameterFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("======== Init ParameterFilter ========");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("======== Do ParameterFilter ========");

        // 将 request、response 转化
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        // 构造 httpservletrequestwarper 对象，重写 getparameter 等方法
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
            @Override
            public String getParameter(String name) {
                String value = httpRequest.getParameter(name);
                return value.replaceAll("fuck", "***");
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = httpRequest.getParameterValues(name);
                return Arrays
                        .asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck", "***"))
                        .toArray(String[] :: new);
            }
        };

        chain.doFilter(wrapper, httpResponse);
    }

    @Override
    public void destroy() {
        LOGGER.debug("======== Destroy ParameterFilter ========");
    }
}